<?php

namespace app\api\controller\wanlshop;

use app\api\service\ActivityService;
use app\api\service\PerformanceService;
use app\api\service\PromoteService;
use app\api\service\UserService;
use app\common\controller\Api;
use addons\wanlshop\library\EasyWeChat\Easywechat;
use addons\wanlshop\library\WanlChat\WanlChat;

use app\common\library\Sms;
use app\common\model\UserExtra;
use fast\Random;
use fast\Http;

use think\Validate;
use think\db;
use think\Log;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * WanlShop会员接口
 */
class Prize extends Api
{
    protected $noNeedLogin = ["slicingPrizeDraw","updatePrizeDrawUser","getPrizeList","getMyBlindList","blindDraw"];
    protected $noNeedRight = ['*'];

    public function _initialize(){
        parent::_initialize();
    }


    public function prizeDraw(){
        ini_set('max_execution_time', '0');
        ini_set("memory_limit", "-1");
        set_time_limit(0);

        $user_id = $this->auth->id;
        //查询用户信息
        $user = db("user")->where("id",$user_id)->find();
        //判断用户信息
        if (!$user){
            $this->error("用户信息有误");
        }elseif($user['is_prize_draw'] != 1){
            $this->error("亲！您暂时没有抽奖机会哦！");
        }
        //查询今天抽奖记录
        $log = db("user_money_log")->where("user_id",$user_id)->where('type',"prize_draw")->where('memo',"每日抽奖奖励")->whereTime("createtime","today")->find();
        $prize_draw_reserve = db("prize_draw_reserve")->whereTime("prizetime","today")->where("user_id",$user_id)->find();
        if($log){
            $this->error("亲！您今日已抽过奖,请明日再来!");
        }
        //查询抽奖活动信息
        $prize_draw = db("prize_draw")->where("status",1)->where("deletetime is null")->order("createtime desc")->find();
        if(!$prize_draw || !$prize_draw_reserve || $prize_draw_reserve["receive"] == 1){
            $this->error("亲！您暂时没有抽奖机会哦！要在七天内升级至13星vip才能获得抽奖哈!");
        }
//        //查询本人所有的抽奖积分
//        $prize_score1 = db("user_money_log")->where('type',"prize_draw")->where("user_id",$user_id)->sum("money");
//        $prize_score2 = db("user_money_log")->where('type',"upgrade")->where("user_id",$user_id)->sum("money");
//        if ($prize_score1 + $prize_score2 >= 10000){
//            $this->error("亲！您的积分奖励已超过1万啦！把机会留给别人吧！");
//        }
        $check = 0;
        $score = $prize_draw_reserve["score"];
        $insert = [
            "user_id"       => $user_id,
            "money"         => $score,
            "before"        => $user["money"],
            "after"         => bcadd($user["money"],$score),
            "memo"          => "每日抽奖奖励",
            "type"          => "prize_draw",
            "createtime"    => time(),
        ];
        if($user["save_money"] < $score){
            $my_save_money = $user["save_money"];
        }else{
            $my_save_money = $score;
        }
        $data = "";
        //更新
        Db::startTrans();
        try {
            db("user")->where("id",$user_id)->inc("money",$score)->inc("score",$score)->dec("save_money",$my_save_money)->inc("prize_draw_money",$score)->update(["updatetime"=>time()]);
            db("user_money_log")->insert($insert);
            db("prize_draw_reserve")->where("id",$prize_draw_reserve["id"])->update(["updatetime"=>time(),"receive"=>"1"]);

            $memo = "用户抽奖,消耗可省钱额度!";
            db("user_money_save_log")
                ->insert([
                    'user_id' => $user["id"],
                    'money' => $my_save_money,
                    'before' => $user["save_money"],
                    'after' => bcsub($user["save_money"],$my_save_money,2),
                    'memo' => $memo,
                    'type' => "dircet",
                    "createtime" => time()
                ]);
            $check = 2;
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            Log::error("抽奖失败,原因为:" . $e->getMessage());
            $data = $e->getMessage();
        }
        if($check == 2){
            $this->success("抽奖成功",["score"=>$score,"times"=>0]);
        }else{
            $this->error("抽奖失败",$data);
        }
    }


    public function slicingPrizeDraw(){
        $check_prize_draw_reserve = db("prize_draw_reserve")->whereTime("prizetime","today")->where("receive","1")->count();
        if($check_prize_draw_reserve > 0){
            $this->error("今日已有人抽奖,不可重新生成积分");
        }
        //查询抽奖活动信息
        $prize_draw = db("prize_draw")->where("status",1)->where("deletetime is null")->order("createtime desc")->find();
        if(!$prize_draw){
            $this->error("抽奖活动尚未开启~~ 敬请期待");
        }
        $user_list = db("user")->where("is_prize_draw",1)->select();
        if(count($user_list) == 0){
            $this->error("今日无人达标");
        }
        $score_list = $this->randomSplit($prize_draw["day_score"],count($user_list),$prize_draw["difference"]);
        $insert = [];
        foreach ($user_list as $k => $v){
            $insert[] = [
                "user_id"    => $v["id"],
                "score"      => $score_list[$k],
                "receive"    => "0",
                "createtime" => time(),
                "prizetime"  => time()
            ];
        }
        $number = 0;
        //更新
        Db::startTrans();
        try {
            db("prize_draw")->where("id",$prize_draw["id"])->update(["day_lowest"=>min($score_list),"day_highest"=>max($score_list),"day_number"=>count($user_list),"updatetime"=>time()]);
            db("prize_draw_reserve")->whereTime("prizetime","today")->delete();
            $number = db("prize_draw_reserve")->insertAll($insert);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            Log::error("生成失败,原因为:" . $e->getMessage());
        }
        if($number != 0){
            $this->success("生成成功",["all_number"=>$number]);
        }else{
            $this->error("生成失败");
        }
    }

    private function randomSplit($total,$parts,$num) {
        $result = [];
        //计算平均值
        $average   = floor(bcdiv($total,$parts,2));
        //循环先随机分配一部分积分(由于向下取整 总积分必定少于等于设定的积分值)
        for ($i = 0; $i < $parts; $i++) {
            if($i % 2 == 0){
                $size = $size_check = mt_rand(bcsub($average,$num),$average);
                if($size <= 0){
                    $size = $size_check = 1;
                }
            }else{
                $size = $average * 2 - $size_check;
            }
            $result[] = $size;
        }
        //计算总积分值
        $total_num = array_sum($result);
        //计算尚有多少积分未分配
        $difference = $total - $total_num;
        if($difference != 0){
            //循环给数据加上多出来的积分
            for ($i = 0; $i < $difference; $i++) {
                if(isset($result[$i])){
                    $result[$i]++;
                }
            }
        }
        // 打乱数组顺序，使分配更随机
        shuffle($result);
        return $result;
    }


    public function updatePrizeDrawUser() {
        ini_set('max_execution_time', '0');
        ini_set("memory_limit", "-1");
        set_time_limit(0);

        //定义升星商品id
        $goods_id_arr = [24, 23, 22, 21, 20, 19, 16, 9, 15, 14, 13, 4, 11];
        //获取13星且无抽奖权限人数
        $user_list1 = db("user")->where("star",13)->where("is_prize_draw",0)->column("id");
        $time = date("Ymd");
        $timestamp = strtotime($time);
        $list_1 = [];
        foreach($user_list1 as $v1){
            //获取昨日下单的所有商品
            $myYesterdayOrder = db("wanlshop_order")
                ->alias("order")
                ->join('wanlshop_order_goods goods','order.id = goods.order_id')
                ->where("order.user_id",$v1)
                ->where("goods.goods_id","in",$goods_id_arr)
                ->where("order.state","in",[2,3,4,6])
                ->group("goods.goods_id")
                ->where("order.createtime","between",[$timestamp - 3 * 86400,$timestamp])
                ->column("goods.goods_id");
                // ->select();
            //比对是否从一星买到十三星
            if($myYesterdayOrder){
                $check_my_direct = db("user")
                    ->where("direct_push",$v1)
                    ->where("createtime","between",[$timestamp - 33 * 86400,$timestamp])
                    ->where("star",13)
                    ->where("lamp",1)
                    ->count();
                $intersect = array_intersect($myYesterdayOrder, $goods_id_arr);
                if (count($goods_id_arr) == count($intersect) && $check_my_direct >= 3){
                    $list_1[] = $v1;
                }
            }

        }

        //有抽奖权限 判断是否已经抽满一万(包含佣金和管理费)
        $user_list2 = db("user")->where("star",13)->where("is_prize_draw",1)->column("id");
        $list_2 = [];
        foreach($user_list2 as $v2){
            $prize_score1 = db("user_money_log")->where('type',"prize_draw")->where("user_id",$v2)->sum("money");
            $prize_score2 = db("user_money_log")->where('type',"upgrade")->where("user_id",$v2)->sum("money");
            if ($prize_score1 + $prize_score2 >= 10000){
                $list_2[] = $v2;
            }
        }
        // return json([$list_1,$list_2]);
        db("user")->where("id","in",$list_1)->update(["is_prize_draw"=>1,'updatetime'=>time()]);
        db("user")->where("id","in",$list_2)->update(["is_prize_draw"=>2,'updatetime'=>time()]);
        $this->success("完成",[$list_1,$list_2]);
    }

    public function getPrizeList(){
        //获取用户信息
        // $user_id = $this->auth->id;
        // //查询用户信息
        // $user = db("user")->where("id",$user_id)->find();
        // //判断用户信息
        // if (!$user){
        //     $this->error("用户信息有误");
        // }
        //查询今天抽奖记录
        $log = db("user_money_log")->order("createtime desc")->where('type',"prize_draw")->limit(50)->select();
        if(count($log) == 0){
            $this->error("暂无抽奖记录");
        }else{
            $return = [];
            foreach ($log as $v){
                $user  = db("user")->where("id",$v["user_id"])->find();
                if($user){
                    $username = $user["username"];
                    // return json(mb_strlen($username));
                    if(mb_strlen($username) >= 11){
                        $username = mb_substr($username, 0, 3)."***".mb_substr($username,-4);
                    }elseif (mb_strlen($username) <= 2) {
                        $username = mb_substr($username, 0, 1)."*";
                    }else{
                        $username = mb_substr($username, 0, 1)."*".mb_substr($username,-1);
                    }
                    $return[] = [
                        "username" => $username,
                        "mobile"   => $this->desMobile($user["mobile"]),
                        "money"    => $v["money"]
                    ];
                }
            }
            $this->success("获取成功",$return);
        }
    }

    private function desMobile($mobile)
    {
        if (strlen($mobile) != 11) {
            return $mobile; // 如果手机号长度不是11位，直接返回原手机号
        }
        return mb_substr($mobile, 0, 3) . '****' . mb_substr($mobile, -4);
    }

    public function getMyBlindList(){
        //获取用户信息
        $user_id = $this->auth->id;
        //查询用户信息
        $user = db("user")->where("id",$user_id)->find();
        //判断用户信息
        if (!$user){
            $this->error("用户信息有误");
        }
        $page = input("param.page");
        if(!$page){
            $page = 1;
        }
        $prize_score1 = db("user_money_log")->where('type',"prize_draw")->where("user_id",$user_id)->sum("money");
        $prize_score2 = db("user_money_log")->where('type',"upgrade")->where("user_id",$user_id)->sum("money");
        if ($prize_score1 + $prize_score2 >= 10000){
            $this->success("成功",[]);
            $this->error("亲！您的积分奖励已超过1万啦！把机会留给别人吧！");
        }
        //查询今天抽奖记录
        $log = db("user_blind")->where("user_id",$user["id"])->limit(($page - 1) * 10,10)->where("status",0)->order("createtime desc")->where("remaintimes","<>",0)->select();
        if(count($log) == 0){
            $this->success("暂无盲盒",[]);
        }else{
            $return = [];
            foreach ($log as $v){
                $log = db("user_money_log")->where("user_id",$user_id)->where("service_ids",$v["id"])->where('memo',"盲盒奖励")->where('type',"prize_draw")->whereTime("createtime","today")->find();
                if($log){
                    $status = 0;
                        $return[] = [
                        "id" => $v["id"],
                        "score"   => $v["oncescore"],
                        "status" => $status
                    ];
                }else{
                    $status = 1;
                    $ccc = [
                        "id" => $v["id"],
                        "score"   => $v["oncescore"],
                        "status" => $status
                    ];
                    array_unshift($return,$ccc);
                }
                
            }
            $this->success("获取成功",$return);
        }
    }

    public function blindDraw(){
        ini_set('max_execution_time', '0');
        ini_set("memory_limit", "-1");
        set_time_limit(0);

        $user_id = $this->auth->id;
        //查询用户信息
        $user = db("user")->where("id",$user_id)->find();
        //判断用户信息
        if (!$user){
            $this->error("用户信息有误");
        }elseif($user["save_money"] <= 0){
            $this->error("用户可用抽盲盒额度为0");
        }
//        elseif(empty($user["blind_times"])){
//            $this->error("用户可用抽盲盒次数为0,请购物增加盲盒次数");
//        }elseif($user["blind_times"] == 34){
//            $this->error("今天刚刚购物,请不要心急,明日才有盲盒次数哦");
//        }
        $now = strtotime(date("Ymd"));
//        $id = input("param.id");
        //查询今天抽奖记录
        $log = db("user_money_log")->where("user_id",$user_id)->where('memo',"盲盒奖励")->where('type',"prize_draw")->whereTime("createtime","today")->find();
        if($log){
            $this->error("亲！您今日已抽取过该盲盒,请明日再来!");
        }
        //查询抽奖活动信息
        $money = null;//db("user_blind_log")->where("blindtime",$now)->find();
        $m = bcmul(db("user_blind_log")->sum("money"), 0.03,2) - db("user_blind_log")->sum("use_money");
        if($m <= 0){
            $this->error("亲！今日盲盒已抽完,请明日再来!!",$m);
        }
        $money["money"] = db("user_blind_log")->sum("money") - db("user_blind_log")->sum("use_money");
        $money["use_money"] = db("user_blind_log")->sum("use_money");
        $money["money"] = bcmul($money["money"], 0.03,2);

        if($money["money"] <= 0){
            $this->error("亲！今日盲盒已抽完,请明日再来!");
        }

        $times = db("user")
            ->where("lamp",1)
//            ->where("save_money",">",0)
//            ->where("blind_times",">",0)
//            ->where("blind_times","<",34)
            ->sum("save_money");
        $check = 0;
        $score = bcmul(bcdiv($money["money"],$times,4) , $user["save_money"],2);
        if($score > $user["save_money"]){
            $score = $user["save_money"];
        }
        if($score > $money["money"] - $money["use_money"]){
            $score = $money["money"] - $money["use_money"];
        }

        $insert = [
            "user_id"       => $user_id,
            "money"         => $score,
            "before"        => $user["money"],
            "after"         => bcadd($user["money"],$score),
            "memo"          => "盲盒奖励",
//            "service_ids"   => $id,
            "type"          => "prize_draw",
            "createtime"    => time(),
        ];
        $data = "";
        //更新
        Db::startTrans();
        try {
            db("user_money_log")->insert($insert);
            $memo = "用户盲盒抽奖,消耗可省钱额度!";
            if ($user["save_money"] - $score < 0){
                db("user")
                    ->where("id",$user_id)
                    ->inc("money",$score)
                    ->inc("score",$score)
                    ->inc("blind_draw_money",$score)
                    ->inc("use_save_money",$user["save_money"])
                    ->update(["updatetime"=>time(),"save_money"=>0]);

            }else{
                db("user")
                    ->where("id",$user_id)
                    ->inc("money",$score)
                    ->inc("score",$score)
                    ->inc("blind_draw_money",$score)
                    ->inc("use_save_money",$score)
                    ->dec("save_money",$score)
                    ->dec("blind_times")
                    ->update(["updatetime"=>time()]);
            }
            db("user_blind_log")
                ->where("blindtime",$now)
                ->inc("use_money",$score)
                ->update(["updatetime"=>time()]);
            db("user_money_save_log")
                ->insert([
                    'user_id' => $user["id"],
                    'money' => $score,
                    'before' => $user["save_money"],
                    'after' => ($user["save_money"] - $score) < 0 ? 0 : bcsub($user["save_money"],$score,2),
                    'memo' => $memo,
                    'type' => "dircet",
                    "createtime" => time()
                ]);
//            db("user_blind")->where("id",$id)->inc("usetimes")->dec("remaintimes")->update(["updatetime"=>time()]);
            $check = 2;
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            Log::error("盲盒抽取失败,原因为:" . $e->getMessage());
            $data = $e->getMessage();
        }
        if($check == 2){
            $this->success("盲盒抽取成功",["score"=>$score]);
        }else{
            $this->error("盲盒抽取失败",$data);
        }
    }




}